// 路由鉴权
import router from "@/router";
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import useUserStore from "@/store/modules/user.ts";
import setting from "@/setting.ts";
import pinia from "@/store";

let userStore = useUserStore(pinia)
nprogress.configure({ showSpinner: false})
// 全局前置守卫
router.beforeEach(async (to, from, next) => {
    document.title = setting.title + '-' + to.meta.title
    nprogress.start()
    let token = userStore.token
    let username = userStore.userInfo.username
    if (token) {
        if (to.path === '/login') {
            next({path: '/'})
        } else {
            if (username) {
                next()
            } else {
              try {
                  await userStore.userInfoStore()
                  next({...to, replace: true})
              }  catch (e) {
                  // token过期
                  await userStore.userLogout()
                  next({path: '/login', query: {redirect: to.path}})
              }
            }
        }
    } else {
        if (to.path === '/login') {
            next()
        } else {
            next({path: '/login', query: {redirect: to.path}})
        }
    }
})
// 全局后置后卫
router.afterEach((to, from) => {
    nprogress.done()
})
